package com.qf.user.controller;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.qf.common.entity.Result;
import com.qf.common.entity.StatusCode;
import com.qf.user.service.TUserService;
import com.qf.user.utils.HttpUtils;
import com.transferbank.user.pojo.TUser;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/****
 * @Author:shenkunlin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/

@RestController
@RequestMapping("/tUser")
@CrossOrigin
public class TUserController {

    @Autowired
    private TUserService tUserService;

    @RequestMapping("/all")
    public void test() {
        System.out.println("测试。。。。。。。。。。");
    }



    /***
     * TUser分页条件搜索实现
     * @param tUser
     * @param page
     * @param size
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "每页显示条数", required = true, dataType = "Integer")
    })
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false) @ApiParam(name = "TUser对象",value = "传入JSON数据",required = false) TUser tUser, @PathVariable  int page, @PathVariable  int size){
        //调用TUserService实现分页条件查询TUser
        PageInfo<TUser> pageInfo = tUserService.findPage(tUser, page, size);
        return new Result(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * TUser分页搜索实现
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @ApiOperation(value = "TUser分页查询",notes = "分页查询TUser方法详情",tags = {"TUserController"})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "page", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "size", value = "每页显示条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
        //调用TUserService实现分页查询TUser
        PageInfo<TUser> pageInfo = tUserService.findPage(page, size);
        return new Result<PageInfo>(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * 多条件搜索品牌数据
     * @param tUser
     * @return
     */
    @ApiOperation(value = "TUser条件查询",notes = "条件查询TUser方法详情",tags = {"TUserController"})
    @PostMapping(value = "/search" )
    public Result<List<TUser>> findList(@RequestBody(required = false) @ApiParam(name = "TUser对象",value = "传入JSON数据",required = false) TUser tUser){
        //调用TUserService实现条件查询TUser
        List<TUser> list = tUserService.findList(tUser);
        return new Result<List<TUser>>(true,StatusCode.OK,"查询成功",list);
    }

    /***
     * 根据ID删除品牌数据
     * @param id
     * @return
     */
    @ApiOperation(value = "TUser根据ID删除",notes = "根据ID删除TUser方法详情",tags = {"TUserController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Long")
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Long id){
        //调用TUserService实现根据主键删除
        tUserService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /***
     * 修改TUser数据
     * @param tUser
     * @param id
     * @return
     */
    @ApiOperation(value = "TUser根据ID修改",notes = "根据ID修改TUser方法详情",tags = {"TUserController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Long")
    @PutMapping(value="/{id}")
    public Result update(@RequestBody @ApiParam(name = "TUser对象",value = "传入JSON数据",required = false) TUser tUser,@PathVariable Long id){
        //设置主键值
        tUser.setPkAdminUid(id);
        //调用TUserService实现修改TUser
        tUserService.update(tUser);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    /***
     * 新增TUser数据
     * @param tUser
     * @return
     */
    @ApiOperation(value = "TUser添加",notes = "添加TUser方法详情",tags = {"TUserController"})
    @PostMapping
    public Result add(@RequestBody  @ApiParam(name = "TUser对象",value = "传入JSON数据",required = true) TUser tUser){
        //调用TUserService实现添加TUser
        tUserService.add(tUser);
        return new Result(true,StatusCode.OK,"添加成功");
    }

    /***
     * 根据ID查询TUser数据
     * @param id
     * @return
     */
    @ApiOperation(value = "TUser根据ID查询",notes = "根据ID查询TUser方法详情",tags = {"TUserController"})
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", required = true, dataType = "Long")
    @GetMapping("/{id}")
    public Result<TUser> findById(@PathVariable Long id){
        //调用TUserService实现根据主键查询TUser
        TUser tUser = tUserService.findById(id);
        return new Result<TUser>(true,StatusCode.OK,"查询成功",tUser);
    }

    /***
     * 查询TUser全部数据
     * @return
     */
    @ApiOperation(value = "查询所有TUser",notes = "查询所TUser有方法详情",tags = {"TUserController"})
    @GetMapping
    public Result<List<TUser>> findAll(){
        //调用TUserService实现查询所有TUser
        List<TUser> list = tUserService.findAll();
        return new Result<List<TUser>>(true, StatusCode.OK,"查询成功",list) ;
    }

    /**
     * 用户登陆功能
     * @param ukPhone
     * @param userPassword
     * @param model
     * @return
     */
    @GetMapping("/login")
    public Result userLogin(String ukPhone, String userPassword , Model model) throws URISyntaxException {
        if (null==ukPhone){
            return new Result(true,StatusCode.LOGINERROR,"ukPhone格式错误!");//"ukPhone格式错误!"
        }
        TUser tUser = tUserService.findukPhone(ukPhone);
        if (null == tUser){
            return new Result(true,StatusCode.LOGINERROR,"用户不存在!");//"用户不存在!"
        }
        if (userPassword.equals(tUser.getUserPassword())){
            model.addAttribute("tUser",tUser );
            return new Result(true,StatusCode.OK,"登陆成功!",tUser);//"登陆成功!"
        }else {
            return new Result(true,StatusCode.LOGINERROR,"密码错误!");//"密码错误!"
        }

    }

    String code = "123456";
    /**
     * 获取发送短信请求, 将验证码发送到对应的手机号码
     * @param
     * @return
     */
    @GetMapping("/getMessage")
    public Result sendMessage(String ukPhone) { //, HttpServletResponse response1
        if (null!=tUserService.findukPhone(ukPhone)){
            return new Result(true,StatusCode.LOGINERROR,"用户已存在!");
        }

        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "49298c576fcd4f03a5d8e4542ff71dd4";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();

        String code2 = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
        code = code2;
        System.out.println(code);
        bodys.put("content", "code:"+code2+",expire_at:5");

        bodys.put("phone_number", ukPhone);
        bodys.put("template_id", "TPL_0001");


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);





            //System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            Map map = JSON.parseObject(EntityUtils.toString(response.getEntity()), Map.class);
            Object status = map.get("status");
            if ("OK".equals(status)){
                //Cookie cookie = new Cookie("code",code );
                //cookie.setMaxAge(60);
                //response1.addCookie(cookie);
                return new Result(true,StatusCode.OK ,"验证码发送成功" );
            }else {
                return new Result(true,StatusCode.OK ,"验证码发送失败" );
            }
            /**
             * {
             *   "request_id": "TID8bf47ab6eda64476973cc5f5b6ebf57e",
             *   "status": "OK"
             * }
             */
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @PostMapping("/register")
    public Result register(@RequestBody TUser tUser,@RequestParam("code") String code1) {// ,ServerHttpRequest request
        if (code1 == null){
            return new Result(true,StatusCode.ERROR,"请输入验证码");
        }
        else if (!code.equals(code1)){
            return new Result(true,StatusCode.ERROR,"验证码不匹配");
        }else if (code.equals(code1)){
            tUserService.add(tUser);

            return new Result(true,StatusCode.OK,"注册成功!");
        }
        return null;
    }
}
